import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/msg/model/alarm_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';

class MsgPage extends ConsumerStatefulWidget {
  const MsgPage({super.key});

  @override
  ConsumerState<MsgPage> createState() => _MsgPageState();
}

class _MsgPageState extends ConsumerState<MsgPage> {
  late EasyRefreshController _refreshController;

  List<AlarmData> _alarmList = <AlarmData>[];
  int _total = 0;
  int _pageNum = 1;
  bool showLoading = true;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _fetchAlarmList(true);
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  Future _fetchAlarmList(bool isRefresh) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.expired == true) {
      setState(() {
        showLoading = false;
        _pageNum = 1;
        _alarmList = <AlarmData>[];
      });
      _refreshController.finishRefresh();
      return;
    }
    final postData = {
      'deviceId': deviceInfo.imei,
      'pageNum': _pageNum,
    };
    final res = await post<AlarmListResp, AlarmListResp>('/deviceAlarm/list',
        data: postData, decodeType: AlarmListResp());
    setState(() {
      showLoading = false;
    });
    res.when(success: (resp) {
      if (resp.code == 200) {
        if (isRefresh) {
          _alarmList = resp.rows ?? [];
          _total = resp.total!;
          _refreshController.finishRefresh();
          _pageNum++;
        } else {
          // 判断是否还有数据
          if (resp.rows!.isEmpty) {
            _refreshController.finishLoad(IndicatorResult.noMore);
            return;
          } else {
            _pageNum++;
            _alarmList.addAll(resp.rows!);
            _refreshController.finishLoad();
          }
        }
        setState(() {});
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取告警列表失败 code: $code msg: $msg');
    });
  }

  _showLoading() {
    if (showLoading) {
      return Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(
          color: AppTheme.themeConfig.primaryColor,
        ),
      );
    } else {
      return _buildListView();
    }
  }

  _listBuilder() {
    return ListView.builder(
        itemCount: _alarmList.length,
        itemBuilder: (context, index) {
          AlarmData alarmData = _alarmList[index];
          // 时间格式化
          final dateStr =
              DateUtil.formatDate(alarmData.occurTime!, format: 'yyyy-MM-dd');
          final timeStr =
              DateUtil.formatDate(alarmData.occurTime!, format: 'HH:mm:ss');

          return Container(
              // height: 50,
              margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
              padding: const EdgeInsets.only(
                  left: 20, right: 20, top: 12, bottom: 12),
              decoration: BoxDecoration(
                color: AppTheme.themeConfig.navBarColor,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          alarmData.warnDesc ?? '',
                          style: TextStyle(
                            fontSize: 16,
                            color: AppTheme.themeConfig.primaryTextColor,
                          ),
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Text(
                          '${alarmData.deviceName}(${alarmData.deviceId})',
                          style: TextStyle(
                            fontSize: 12,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      // 日期分两行
                      Text(
                        dateStr,
                        style: TextStyle(
                          fontSize: 12,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                      Text(
                        timeStr,
                        style: TextStyle(
                          fontSize: 12,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ],
                  ),
                ],
              ));
        });
  }

  _buildListView() {
    return Container(
      color: Colors.white,
      child: EasyRefresh(
          controller: _refreshController,
          onRefresh: () async {
            _pageNum = 1;
            _fetchAlarmList(true);
          },
          onLoad: () async {
            _fetchAlarmList(false);
          },
          child: Stack(
            children: [
              _listBuilder(),
              Offstage(
                offstage: _alarmList.isNotEmpty,
                child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    '暂无告警消息',
                    style: TextStyle(
                      fontSize: 16,
                      color: AppTheme.themeConfig.infoTextColor,
                    ),
                  ),
                ),
              ),
            ],
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('消息', style: TextStyle(fontSize: 18)),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.navBarColor,
        foregroundColor: Colors.white,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            height: kToolbarHeight,
            padding: const EdgeInsets.only(top: 8),
            alignment: Alignment.center,
            child: const Text(' <返回',
                textAlign: TextAlign.center,
                maxLines: 1,
                style: TextStyle(color: Colors.black)),
          ),
        ),
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: _showLoading(),
    );
  }
}
